<template>
<div class='noTouch-containers' >
    <div class="evid-l">
      <div class="evid-wrap">
        <div class="evid-type receive-costTitle">文件列表</div>
        <div class="evid-box">
          <template >
            <div
              v-for="(treeDoc) in documentTree"
              :key="treeDoc.treeId"
              class="evid-con"
            >
              <div class="evid-first">
                <div v-if="treeDoc.treeDocList && treeDoc.treeDocList.length" class="tree-check-icon" :class="{'active' : treeDoc.checked}" @click.stop="handleFirstNameCheck(treeDoc)" />
                <div class="evid-firstKey">{{ treeDoc.treeName }}</div>
              </div>
              <div class="evid-secondBox">
                <div
                  v-for="(document) in treeDoc.treeDocList"
                  :key="document.id"
                  class="evid-second"
                  :class="{ active: document.id === currentDocId }"
                  @click="
                    clickDocName(document.id, treeDoc, document)
                  "
                >
                  <div class="evid-secondKey" :title="document.docName">
                    <div
                      v-show="!document.error"
                      class="tree-check-icon"
                      :class="{'active' : document.checked}"
                      @click.stop="handleNameCheck(treeDoc, document)"
                    />
                    {{ document.docName }}
                  </div>
                  <span v-if="imageMaps[document.id] && imageMaps[document.id].length" class="complete el-icon-circle-check" />
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
     <div class="noTouch-signBox">
      <div ref="noTouchSignCon" class="noTouch-signCon">
        <div id="pdf_view_wrapper" style="position: relative">
          <div  style="position: absolute">
            <div
              v-for="key of docList"
              :id="'drag_container'+key"
              :key="key"
              style="position: relative;overflow: hidden"
              :style="dragPositions[key] || dragPosition"
            >
              <VueDragResize
                v-for="(item, index) in imageMaps[key]"
                v-show="!item.isDeleted"
                :key="item.id || index"
                :x="item.left"
                :y="item.top"
                :w="item.width"
                :h="30"
                :parent-w="divWidth"
                :parent-h="parseInt(dragPositions[key].height)"
                axis="both"
                :parent-limitation="true"
                :is-active="true"
                :is-draggable="true"
                :is-resizable="false"
                @dragstop="dragEnd($event, index, key)"
              >
                <!-- <template v-if="item.isCompany">
                  <div class="noTouch-signName company-img" />
                  <div class="noTouch-signKey">公章</div>
                </template>
                <template v-else>
                  <div class="noTouch-setSign">
                    <span v-for="(word, wi) in item.cnName" :key="wi">{{ word }}</span>
                  </div>
                  <div class="noTouch-signKey">
                    {{ item.roleName }}
                  </div>
                </template> -->
              </VueDragResize>
            </div>
          </div>
              <!-- 文书列表 -->
          <div v-for="key of docList" :key="key" class="files-canvas">
            <canvas
              v-for="page of docNumPages[key]"
              :id="`pdf_view${key}_${page}`"
              :key="`${key}-${page}`"
              :ref="`pdf_viewer${key}_${page}`"
              :attrId="key"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 签章区域 -->
        <div class="noTouch-signCont">
      <div class="no-touch-btn">
        <!-- <el-button type="primary" class="close-btn" @click="oneAdd">一键添加</el-button> -->
        <el-button type="primary" class="close-btn" @click="oneDelete">一键删除</el-button>
        <el-button type="primary" class="close-btn" @click="closeShowBack">完成</el-button>
      </div>
      <div class="noTouch-signTop">
        <div class="receive-costTitle noTouch-signL">当事人</div>
        <div class="noTouch-signS">拖动姓名框可设置签署位</div>
        <el-button class="tool-btn" style="height:32px" @click="oneAdd">一键添加</el-button>
      </div>
      <div
        v-for="person in personData"
        :key="person.id + person.subject"
        class="noTouch-signPerson"
        style="z-index: 1"
        @mousedown="handleDown(person, $event)"
      >
        <div style="position:relative;">
          <el-popover
            v-model="signVisible[person.id]"
            placement="top-start"
            width="200"
            trigger="manual"
            content="是事项关联的当事人"
            popper-class="popover-container-black"
          >
            <div v-if="person.notaryItemId" slot="reference" class="noTouch-signStar" @click="handlePopover(person.id)" />
          </el-popover>
        </div>
        <div class="noTouch-signName"><!-- {{ person.cnName }} -->
          <span v-for="(word, wi) in person.cnName" :key="wi">{{ word }}</span>
        </div>
        <div class="noTouch-signKey">
          {{ person.resName }}
        </div>
      </div>
      <div
        v-for="person in companyData"
        :key="person.id + person.subject"
        class="noTouch-signCompany"
        style="z-index: 1"
      >
        <div
          v-if="person.customerType === 2 && showPerson(person)"
          class="noTouch-sign-wrap"
        >
          <div class="company-name-title">{{ person.cnName }}</div>
          <div
            class="noTouch-sign-item"
            @mousedown="handleDown(person, $event)"
          >
            <div style="position:relative;">
              <el-popover
                v-model="signVisible[person.id]"
                placement="top-start"
                width="200"
                trigger="manual"
                content="是事项关联的当事人"
                popper-class="popover-container-black"
              >
                <div v-if="person.notaryItemId" slot="reference" class="noTouch-signStar" @click="handlePopover(person.id)" />
              </el-popover>
            </div>
            <div class="company-img" />
            <div class="noTouch-signKey">公章</div>
          </div>
          <div
            v-for="item of person.children"
            :key="item.id"
            class="noTouch-sign-item"
            @mousedown="handleDown(item, $event)"
          >
            <div class="noTouch-signName"><!-- {{ item.cnName }} -->
              <span v-for="(word, wi) in item.cnName" :key="wi">{{ word }}</span>
            </div>
            <div class="noTouch-signKey">
              {{ item.resName }}
            </div>
          </div>
        </div>
      </div>
      <div v-if="notaryOnlineSign">
        <div class="noTouch-signTop" style="margin-top: 20px">
          <div class="receive-costTitle noTouch-signL">公证人员</div>
          <div class="noTouch-signS">拖动姓名框可设置签署位</div>
        </div>
        <div
          v-for="person in notaryPersonList"
          :key="person.id"
          class="noTouch-signPerson"
          style="z-index: 1"
          @mousedown="handleDown(person, $event)"
        >
          <div class="noTouch-signName">
            <!-- {{ person.cnName }} -->
            <span v-for="(word, wi) in person.cnName" :key="wi">{{ word }}</span>
          </div>
          <div class="noTouch-signKey">
            {{ person.resName }}
          </div>
        </div>
      </div>
    </div>
</div>
</template>

<script>
import { documentTree, findNotaryFileItemPersonRes, findNotaryPerson } from './assets/data.js'
import pdfjs from 'pdfjs-dist'
export default {
  name: 'signatureDrag',
  props: {},
  components: {},
  data () {
    return {
    canvasShow: true,
    doc: null,
    scale: 0.9,
    pdfUrl: 'https://notary-cloud-test.obs.cn-south-1.myhuaweicloud.com:443/anonymous/2022/08/20/17/4daf3e98dcee4b6b9c29fde8d5a89d84.pdf?AccessKeyId=PRLK09QAHY6JCEO7YLMB&Expires=1661222646&Signature=jYM6dEm3bd7iMcPH7HxrQtaDOu8%3D',
    pdfDoc: null,
    imageMaps: {},
    docInfos: {},
    findNotaryFileItemPersonRes,
    notaryPersonList: findNotaryPerson,
    docList: [], // 文件列表
    docNumPages: {},
    currentDocId: undefined,
    firstJoin: true,
    currentDocTemp: {}, // 当前文档对象
    dragPositions: {}, // 拖拽签章位置
    documentTree: documentTree // 文件列表
    }
  },
  computed: {
  },
  created () {
    this.getPersonByFile()
    this.loadAllDoc(this.documentTree)
    pdfjs.GlobalWorkerOptions.workerSrc = 'pdfjs-dist/build/pdf.worker.js'
  },
  mounted () {
    this.$nextTick(() => {
      if (document.querySelector('.noTouch-signCon')) {
        document.querySelector('.noTouch-signCon')
          .addEventListener('mousewheel', this.handleMousewheel)
      }
    })
  },
  methods: {
        /**
     * 加载pdf文件
     */
    initPdfComponent (fileId) {
      this.imageMap = []
    //   loading.text = '拼命加载中...'
    //   this.pdfFileViewUrl = this.dowmPdfFile + '?fileId=' + pdfFileId + '&_t=' + Math.random()
      const loadingTask = pdfjs.getDocument({ url: this.pdfUrl })
      loadingTask.promise
        .then((pdf) => {
          this.doc = pdf
          this.$set(this.docNumPages, fileId, pdf.numPages)
          this.currentPage = 1
          this.$nextTick(() => {
            for (let i = 1; i <= this.docNumPages[fileId]; i++) {
              this.renderPage(i, fileId)
            }
          })
        })
        .catch(() => {
          this.loadPdf = false
          if (this.tabValue === 'file') {
            this.docInfos[fileId].error = true
          }
        })
    },
        /**
     * 页码切换
     */
    renderPage (currentPage, fileId) {
      this.doc.getPage(currentPage).then((page) => {
        const defViewport = page.getViewport({ scale: 1 })
        const width = this.$refs.noTouchSignCon.offsetWidth || 800
        const scale = (width / defViewport.width).toFixed(2)
        const viewport = page.getViewport({ scale }) || {}
        // const viewport = page.getViewport({ scale: scale })
        const canvas = document.getElementById(`pdf_view${fileId}_${currentPage}`)
        const context = canvas.getContext('2d')
        canvas.height = viewport.height
        canvas.width = viewport.width
        const pdf_viewerRef = this.$refs[`pdf_viewer${fileId}_${currentPage}`][0]
        this.divWidth = pdf_viewerRef.width
        let { height } = this.dragPositions[fileId] || {}
        if (currentPage === 1) {
          height = pdf_viewerRef.height + 'px'
          // this.divHeight = pdf_viewerRef.height
        } else {
          height = parseFloat(height) + pdf_viewerRef.height + 'px'
          // this.divHeight += pdf_viewerRef.height
        }
        this.$set(this.dragPositions, fileId, { width: pdf_viewerRef.width + 'px', height, left: pdf_viewerRef.offsetLeft + 'px' })
        const renderContext = {
          canvasContext: context,
          viewport: viewport
        }
        page.render(renderContext)
        if (fileId) {
          this.loadSign(this.notaryFileVo.id, fileId, this.currentPage)
        }
      })
    },
      /* 拖拽结束 - 调整跨页 */
    dragEnd (newRect, index, key) {
      this.imageMaps[key][index].signX = newRect.left
      this.imageMaps[key][index].signY = newRect.top
      this.imageMaps[key][index].top = newRect.top

      const numPages = this.docNumPages[key]
      const top = this.imageMaps[key][index].signY
      const height = parseInt(this.dragPositions[key].height) / numPages
      // const height = parseInt(this.imageMaps[key][index].height) / numPages
      this.imageMaps[key][index].signPage = Math.ceil(newRect.top / height)
      const offsety = 30
      for (let i = 1; i < numPages; i++) {
        const h = height * i
        if (h > top && h < top + offsety) {
          const temp = {
            ...this.imageMaps[key][index],
            signY: h - offsety,
            top: h - offsety,
            signPage: i
          }
          this.imageMaps[key][index] = temp
          newRect.top = h - offsety
          document.querySelector('#drag_container').querySelectorAll('.vdr')[ index ].style.top = h - offsety + 'px'
          break
        }
      }
      // 拖拽完成保留签章的位置
    //   saveNotarySmallDocSign(this.imageMaps[key][index]).then((res) => {
    //     if (res.code !== 0) {
    //       this.$message.error(res.message)
    //     }
    //   })
    },
      /**
     * 单击文件名
     */
    clickDocName (id, parent, row) {
      if (this.currentDocTemp.id === id) return
      const doc = this.docInfos[id] || {}
      if (doc.error) {
        this.$message.error(doc.docName + '生成出错，请联系管理员!')
        return
      }
      this.currentItem = parent
      this.currentDocTemp = row
    //   this.checkDocumentBox(parent, row)
      // const to = (document.getElementById('drag_container' + id) || {}).offsetTop
      // const elt = this.$refs.noTouchSignCon
      // this.$utils.scrollTo(to, 500, elt)
    //   this.setCurStatus(id)
      if (this.firstJoin) {
        this.firstJoin = false
        return
      }
      this.loadAllDoc(this.documentTree)
    },
    handleNameCheck () {},
        /**
     * 加载当事人
     */
    getPersonByFile () {
          // 过滤当事人
          const personList = []
            const list = this.findNotaryFileItemPersonRes
            for (let i = 0; i < list.length; i++) {
              if (
                list[i].customerType === 1 &&
                list[i].cnName &&
                list[i].certificateNo
              ) {
                const person = {
                  ...list[i],
                  subject: false,
                  custType: false,
                  agentType: false
                }
                personList.push(person)
              } else if (list[i].customerType === 2) {
                if (list[i].companyCnName && list[i].certificateNo) {
                  const person = JSON.parse(JSON.stringify(list[i]))
                  person.cnName = person.companyCnName
                  person.contactNumber = person.corporationContactNumber
                  person.subject = true
                  person.custType = true
                  person.agentType = false
                  // 企业-公章
                  person.isCompany = true
                  personList.push(person)
                }
                if (
                  list[i].legalPersonName &&
                  list[i].corporationCertificateNo
                ) {
                  const person = JSON.parse(JSON.stringify(list[i]))
                  person.cnName = person.legalPersonName
                  person.certificateNo = person.corporationCertificateNo
                  person.contactNumber = person.corporationContactNumber
                  person.resName = '法定代表人'
                  person.subject = false
                  person.custType = true
                  person.agentType = false
                  personList.push(person)
                }
              }
            }
                 this.personList = personList
          },
    loadAllDoc (data) {
      if (data.length > 0) {
        this.loadPdf = true
        this.canvasShow = false
        this.docInfos = {}
        this.docList = []
        const tempList = []
        console.log(data, 'data', this.currentDoc)

          data.forEach((item) => {
            const treeDocList = item.treeDocList || []
            treeDocList.forEach(async (doc) => {
              tempList.push(doc)
            })
          })
          if (tempList.length > 0) {
            this.currentDocTemp = tempList[0]
          } else {
            // loading.close()
            this.loadPdf = false
            this.firstJoin = false
            return
          }

        data.forEach((item, firstIndex) => {
          const treeDocList = item.treeDocList || []
          if (treeDocList.length < 1) {
            this.loadPdf = false
            // loading.close()
          }
          treeDocList.forEach(async (doc, index) => {
            const { fileId, id } = doc
              this.currentItem = item
              this.currentDocTemp = doc
              const isCommonDoc = item.treeName === '通用文书'
              doc.isCommonDoc = isCommonDoc
              doc.treeId = item.treeId
              this.docInfos[id] = doc
              this.docList.push(id)
                await this.transPdf({ id, index, firstIndex })
          })
        })
      }
    },
    /**
     * 加载文件的签章
     */
    loadSign (notaryFileId, fileId, page) {
          const imageMap = []
          for (const docSign of res.data) {
            let signY = docSign.signY
            const h = parseFloat(this.dragPositions[fileId].height) / this.docNumPages[fileId]
            const preHeight = h * (docSign.signPage - 1)
            if (signY < preHeight) {
              signY += preHeight
            }
            const sign = {
              width: 100,
              height: docSign.isCompany ? 100 : 30,
              isDeleted: false,
              keyword: docSign.signPage,
              signPage: docSign.signPage,
              right: docSign.signX,
              down: signY,
              left: docSign.signX,
              top: signY,
              signX: docSign.signX,
              signY: signY,
              cnName: docSign.personName,
              roleName: docSign.roleName,
              notaryFileId: docSign.notaryFileId,
              personId: docSign.personId,
              fileId: docSign.fileId,
              id: docSign.id,
              isCompany: docSign.unitName === docSign.personName
            }
            imageMap.push(sign)
          }
          this.$set(this.imageMaps, fileId, imageMap)
    },
        /**
     * 转换PDF
     */
    transPdf ({ id, index, firstIndex }) {
      this.canInsert = true
            this.initPdfComponent(id)
            // this.documentTree[firstIndex].treeDocList[index].pdfFileId = res.data
            this.canvasShow = true
          }

  }
}
</script>

<style scoped lang="less">
.noTouch-containers {
    height: calc(100vh - 90px);
    background: #fff;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    overflow: hidden;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.evid-wrap {
  height: calc(100vh - 100px);
  padding: 10px;
  border: 1px solid #e6e6e6;
  overflow: auto;
}
.evid-l{
     background: #fff;
    height: 100%;
    overflow: hidden;
    overflow-y: auto;
    padding: 16px;
    width: 310px;
}
.noTouch-signBox {
    background: #f8f8f8;

    flex: 1;
    padding: 10px 15px;
    position: relative;
}
.noTouch-signBtnBox {
  position: absolute;
  right: -35px;
  top: 50%;
  margin-top: -30px;
  display: flex;
  flex-direction: column;
  z-index: 0;

  .first-page {
    transform: rotate(180deg);
  }

  .el-button {
    margin: 10px 0;
  }

  .el-button.disabled {
    background: rgba(0, 0, 0, 0.1);
  }

  .page-text {
    width: 100%;
    margin-top: 5px;
    padding: 5px;
    display: inline-block;
    background: rgba(0, 0, 0, 0.1);
    text-align: center;
    color: #fff;
  }
}

.vdr.active {
  background: rgba(240, 242, 245, 0.5);
  border-radius: 10px;

  &::before {
    outline: none !important;
  }
}

.noTouch-signBox { .el-loading-mask {
  position: fixed;
}
}

// #pdf_view_wrapper canvas[height] {
//   float: left;
//   height: 841px;
// }

.files-canvas {
  overflow: hidden;
}

// #pdf_view_wrapper canvas[height]:last-child {
//   border-bottom: 1px dashed #000;
// }

.no-touch-btn {
  align-items: center;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.evid-firstKey {
  flex-shrink: 1;
}

.evid-secondKey {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.evid-second{
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    color: #687285;
    cursor: pointer;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    height: 40px;
    justify-content: space-between;
    padding: 0 20px 0 34px;
}

.tree-check-icon {
  float: left;
}

.evid-third {
  position: relative;
  padding-right: 20px;
  .complete {
    position: absolute;
    right: 5px;
    margin-right: 0;
  }
}

.complete {
  color: #67c23a;
  margin-right: -15px;
}
</style>
